package cn.uncode.dal.router;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class TableShardingRouter {
	
	
    private static final ConcurrentMap<String, TableRouter> cache = new ConcurrentHashMap<String, TableRouter>();
    
    public static void setTableRouter(String table, TableRouter tableRouter){
    	cache.putIfAbsent(table, tableRouter);
    }
    
    public static boolean containsTable(String table){
    	return cache.containsKey(table);
    }
    
    public static String getShardingTableById(String table, long id){
    	TableRouter tableRouter = cache.get(table);
    	String tableName = null;
    	if(null != tableRouter){
    		if(SharingType.RANGE.equals(tableRouter.getSharingType())){
    			for(Range range:tableRouter.getRanges()){
    				if(range.getStart()<=id && id <= range.getEnd()){
    					tableName = range.getTableName();
    					break;
    				}
    			}
    		}
    	}
    	return tableName;
    }
    
    public static List<Range> getShardingTables(String table){
    	TableRouter tableRouter = cache.get(table);
    	List<Range> ranges = null;
    	if(null != tableRouter){
    		if(SharingType.RANGE.equals(tableRouter.getSharingType())){
    			ranges = tableRouter.getRanges();
    		}
    	}
    	return ranges;
    }

}
